from django.contrib.auth import login
from django.shortcuts import render, redirect
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django import http
from django.db.models import ObjectDoesNotExist
from django_redis import get_redis_connection
import logging
import re

from utils.response_code import RETCODE
from oauth.models import OAuthUser
from oauth.utils import generate_openid_access_token, check_openid_access_token
from users.models import User
from carts.utils import merge_carts_cookie_redis


# Create your views here.
class QQAuthUserView(View):
    def get(self, request):
        code = request.GET.get('code')
        if not code:
            return http.HttpResponseForbidden('Got code failure')

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI)

        logger = logging.getLogger('django')

        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('Got openid failure')
        # openid = 1234560

        try:
            qq_user = OAuthUser.objects.get(openid=openid)
        except ObjectDoesNotExist:
            access_token_openid = generate_openid_access_token(openid)
            context = {'access_token_openid': access_token_openid}
            return render(request, 'oauth_callback.html', context)
        else:
            login(request, qq_user.user)

            state = request.GET.get('state')
            if not state:
                state = '/'

            response = redirect(state)

            response.set_cookie('username', qq_user.user.username, max_age=3600)

            response = merge_carts_cookie_redis(request=request, response=response, user=user)

            return response



    def post(self, request):
        mobile = request.POST.get('mobile')
        password = request.POST.get('password')
        sms_code_client = request.POST.get('sms_code')
        access_token_openid = request.POST.get('access_token_openid')

        if not all([password, mobile, sms_code_client]):
            return http.HttpResponseForbidden('Missing required parameters')

        if not re.match(r'^[0-9a-zA-Z]{8,20}$', password):
            return http.HttpResponseForbidden('Password needs 8 to 20 characters')

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('Incorrect phone number format')

        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if sms_code_server is None:
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': 'SMS code has expired'})
        if sms_code_client != sms_code_server.decode():
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': 'Incorrect SMS code'})

        openid = check_openid_access_token(access_token_openid)

        if not openid:
            return render(request, 'oauth_callback.html', {'openid_errmsg': 'Openid has expired'})

        try:
            user = User.objects.get(mobile=mobile)
        except ObjectDoesNotExist:
            user = User.objects.create_user(username=mobile, password=password, mobile=mobile)
        else:
            if not user.check_password(password):
                return render(request, 'oauth_callback.html', {'account_errmsg': 'Incorrect user or password'})

        logger = logging.getLogger('django')

        try:
            OAuthUser.objects.create(user=user, openid=openid)
        except Exception as e:
            logger.error(e)
            return render(request, 'oauth_callback.html', {'qq_login_errmsg': 'login failure'})

        login(request, user)

        state = request.GET.get('state')
        if not state:
            state = '/'

        response = redirect(state)
        response.set_cookie('username', user.username, max_age=3600)

        response = merge_carts_cookie_redis(request=request, response=response, user=user)

        return response


class QQAuthLoginView(View):
    def get(self, request):
        next = request.GET.get('next')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        login_url = oauth.get_qq_url()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'login_url': login_url})

